//
//  YTOrderListViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/4/27.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTOrderListViewController.h"
#import "YTOrderFlowViewController.h"
#import "YTLoginViewController.h"
#import "YTNavigationController.h"
#import "YTOrderDetailViewController.h"
#import "YTOrderListViewModel.h"
#import "YTOrderListViewCell.h"
#import "YTOrderFilterView.h"

#import "YTPopupView.h"
#import "YTOrderListModel.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface YTOrderListViewController ()<
UITableViewDelegate,
UITableViewDataSource,
DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate>

@property (nonatomic, strong) YTOrderListViewModel *viewModel;
@property (strong, nonatomic) YTSegmentedControl *segmentControl;
@property (strong, nonatomic) YTPopupView *popView;
@property (weak, nonatomic) IBOutlet UIView *segmentView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) NSInteger index; // 记录每次点击的index，如果接单成功删除这条记录
@end

@implementation YTOrderListViewController

#pragma mark - lifecycle

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 监听是否需要登录
//    @weakify(self);
//    [[[[NSNotificationCenter defaultCenter]
//       rac_addObserverForName:YTUserNeedToLoginNotification object:nil]
//       subscribeOn:[RACScheduler mainThreadScheduler]]
//       subscribeNext:^(id x) {
//           @strongify(self);
//           [SVProgressHUD dismiss]; // 这里可能前面的HUD还没有消失...
           [[NSNotificationCenter defaultCenter] postNotificationName:YTUserNeedToLoginNotification object:nil];
           [self performSegueWithIdentifier:@"YTNeedLogin" sender:nil];
//     }];
}

- (void)initialize {
    self.viewModel = [[YTOrderListViewModel alloc] init];
    _index = 0;
    @weakify(self);
    [self.tableView addLoadDataControl:^{
        @strongify(self);
        [self.viewModel.loadMoreDataCommand execute:nil];
    }];
    
    [self.tableView addRefreshControl:^{
        @strongify(self);
        [self.viewModel.requestRemoteDataCommand execute:nil];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)bindViewModel {
    [super bindViewModel];
    [self userinterfaceControl];
    YTSegmentedControlConfig *config = [[YTSegmentedControlConfig alloc] init];
    config.indecatorWidth = 60;
    config.titleSize = 19;
    _segmentControl = [[YTSegmentedControl alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)
                                                         titles:@[@"全部", @"星级", @"悬赏"]
                                                  configuration:config];
    @weakify(self);
    _segmentControl.didSelectedItem = ^(NSInteger index) {
        @strongify(self);
        [self.viewModel.changeTabCommand execute:@(index)];
    };
    [self.segmentView addSubview:_segmentControl];
    // 加载订单数据和获取用户信息
    [_viewModel.loadUserInfoCommand execute:nil];
    [_viewModel.requestRemoteDataCommand execute:nil];
}

#pragma mark - UI控制

- (void)userinterfaceControl {
    @weakify(self);
    [_viewModel.requestRemoteDataCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    [_viewModel.changeTabCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    [_viewModel.filterCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    [_viewModel.checkOrderCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    
    // 刷新
    void (^refresh)(id x) = ^(NSArray<YTOrderListModel *> *data) {
        @strongify(self);
        [self.tableView setContentOffset:CGPointMake(0, 0)];
        [self.tableView reloadData];
        if (data.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    };
    
    [[_viewModel.requestRemoteDataCommand.executionSignals switchToLatest] subscribeNext:refresh];
    [[_viewModel.changeTabCommand.executionSignals switchToLatest] subscribeNext:refresh];
    [[_viewModel.filterCommand.executionSignals switchToLatest] subscribeNext:refresh];
    [[_viewModel.loadMoreDataCommand.executionSignals switchToLatest]
     subscribeNext:^(NSArray<YTOrderListModel *> *data) {
        @strongify(self);
        if (data.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView reloadData];
    }];
    
    // 检测订单是否被抢
    [[_viewModel.checkOrderCommand.executionSignals switchToLatest]
     subscribeNext:^(NSDictionary *response) {
         @strongify(self);
         NSDictionary *data = response[@"responseData"];
         if ([data[@"driverId"] integerValue] == 0) {
             [self performSegueWithIdentifier:@"YTOrderDetail" sender:self.viewModel.order_id];
         } else {
             [UIAlertView bk_showAlertViewWithTitle:nil message:@"该订单已被抢"
                                  cancelButtonTitle:@"确认" otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                                      [self.navigationController popViewControllerAnimated:YES];
                                  }];
             
         }
    }];
}

#pragma mark - UITableViewDeleagte 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YTOrderListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTOrderListViewCell" forIndexPath:indexPath];
    cell.model = _viewModel.dataSource[indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _viewModel.dataSource.count;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _viewModel.dataSource.count - 10 && _viewModel.dataSource.count >= 20) {
        [tableView.mj_footer beginRefreshing];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 置为已读
    _viewModel.dataSource[indexPath.row].noRead = @"0";
    [tableView reloadData];
    // 进入详情,检测是否被抢
    [self.viewModel.checkOrderCommand execute:_viewModel.dataSource[indexPath.row].orderId];
    _index = indexPath.row;
}

#pragma mark - DZNEmptyDataSetSource

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"当前暂无订单";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0f],
                                 NSForegroundColorAttributeName: kGrayColor};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"public_norecord"];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -100;
}

#pragma mark - action

// 弹出筛选选项
- (IBAction)filteAction:(UIBarButtonItem *)sender {
    [self.popView showWithLayout:YTPopupLayoutMake(YTPopupHorizontalLayoutLeft, YTPopupVerticalLayoutCenter)];
}

- (YTPopupView *)popView {
    YTOrderFilterView *filter = [[YTOrderFilterView alloc] initWithFrame:CGRectMake(0, 0, 270, kScreenHeight)];
    [filter loadCityData:_viewModel.serviceCitys];
    _popView  = [YTPopupView popupWithContentView:filter];
    _popView.showType = YTPopupShowTypeSlideInFromLeft;
    _popView.dismissType = YTPopupDismissTypeSlideOutToLeft;
    @weakify(self);
    filter.completeAction = ^(NSDictionary *dict){ //点击完成
        @strongify(self);
        [_popView dismiss:YES];
        [self.viewModel.filterCommand execute:dict];
    };
    
    filter.resetAction = ^{
        @strongify(self);
        [_popView dismiss:YES];
        [self.viewModel.requestRemoteDataCommand execute:nil];
    };
    
    return _popView;
}

- (BOOL)becomeFirstResponder {
    return YES;
}

#pragma mark - 跳转逻辑

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"YTOrderDetail"]) {
        YTOrderDetailViewController *detail = segue.destinationViewController;
        detail.order_id = sender;
        detail.pickOrderSuccess = ^{ // 删除被抢订单
            [self deletePickedOrder];
        };
    }
}

- (void)deletePickedOrder {
    [_viewModel.dataSource removeObjectAtIndex:_index];
    NSIndexPath *path = [NSIndexPath indexPathForRow:_index inSection:0];
    [_tableView deleteRowsAtIndexPaths:@[path]
                      withRowAnimation:UITableViewRowAnimationFade];
    [_tableView reloadData];
}

@end
